package main

import (
	"net/http"

	"github.com/bmizerany/pat"
	"github.com/justinas/alice"
)

func (app *application) routes() http.Handler {

	//过滤器链
	stardardMiddleware := alice.New(app.recoverPanic, app.logRequest, secureHeaders)

	// Create a new middleware chain containing the middleware specific to
	// our dynamic application routes. For now, this chain will only contain
	// the session middleware but we'll add more to it later.
	//session处理链，不需要在static 路径上处理
	// Use the nosurf middleware on all our 'dynamic' routes.
	//dynamicMiddleware := alice.New(app.session.Enable, noSurf)
	// Add the authenticate() middleware to the chain.
	dynamicMiddleware := alice.New(app.session.Enable, noSurf, app.authenticate)

	//restful api 路由，添加session处理
	mux := pat.New()
	mux.Get("/", dynamicMiddleware.ThenFunc(app.home))

	// Add the requireAuthentication middleware to the chain.
	mux.Get("/snippet/create", dynamicMiddleware.Append(app.requireAuthentication).ThenFunc(app.createSnippetForm))
	// Add the requireAuthentication middleware to the chain.
	mux.Post("/snippet/create", dynamicMiddleware.Append(app.requireAuthentication).ThenFunc(app.createSnippet))

	// mux.Get("/snippet/create", dynamicMiddleware.ThenFunc(app.createSnippetForm))
	// mux.Post("/snippet/create", dynamicMiddleware.ThenFunc(app.createSnippet))
	//注意同一个url的注册顺序,/snippet/create 必须注册在前，否则就会被/snippet/:id捕获
	mux.Get("/snippet/:id", dynamicMiddleware.ThenFunc(app.showSnippet))

	// Add the five new routes.
	mux.Get("/user/signup", dynamicMiddleware.ThenFunc(app.signupUserForm))
	mux.Post("/user/signup", dynamicMiddleware.ThenFunc(app.signupUser))
	mux.Get("/user/login", dynamicMiddleware.ThenFunc(app.loginUserForm))
	mux.Post("/user/login", dynamicMiddleware.ThenFunc(app.loginUser))
	mux.Post("/user/logout", dynamicMiddleware.ThenFunc(app.logoutUser))

	//复用器
	// mux := http.NewServeMux()
	// mux.HandleFunc("/", app.home)
	// mux.HandleFunc("/snippet", app.showSnippet)
	// mux.HandleFunc("/snippet/create", app.createSnippet)

	// Add a new GET /ping route.
	mux.Get("/ping", http.HandlerFunc(ping))
	fileServer := http.FileServer(http.Dir("./ui/static/"))
	mux.Get("/static/", http.StripPrefix("/static", fileServer))
	//mux.Handle("/static/", http.StripPrefix("/static", fileServer))
	// Wrap the existing chain with the recoverPanic middleware.
	//return app.recoverPanic(app.logRequest(secureHeaders(mux)))
	return stardardMiddleware.Then(mux)
}
